const Base = require('./base.js');
const md5 = require('md5');
const redis = require('redis');

Date.prototype.format = function (format) {
    let o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(), //day
        "h+": this.getHours(), //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
        "S": this.getMilliseconds() //millisecond
    };
    if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
        (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o)
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1,
                RegExp.$1.length == 1 ? o[k] :
                    ("00" + o[k]).substr(("" + o[k]).length));
    return format;
};
let urlParse = function (url) {
    //let url = window.location.search;
    let obj = {};
    let reg = /[?&][^?&]+=[^?&]+/g;
    let arr = url.match(reg);
    // ['?id=12345','&a=b']
    if (arr) {
        arr.forEach((item) => {
            let tempArr = item.substr(1).split('=');
            let key = decodeURIComponent(tempArr[0]);
            let val = decodeURIComponent(tempArr[1]);
            obj[key] = val
        })
    }
    return obj
};

module.exports = class extends Base {
    indexAction() {
        return this.display();
    }


    baseDataAction() {
        return this.display();
    }

    async editBaseDataAction() {
        let data = this.post();
        let result = false;
        let db = this.model('basic_data');
        data.last_updated = new Date().format("yyyy-MM-dd hh:mm:ss");
        try {
            let insertId = await db.where({id: data.id}).update(data);
            result = insertId > 0;
        } catch (ex) {
            result = false;
        } finally {
            this.ctx.body = {
                success: result
            };
        }
    }

    async addBaseDataAction() {
        let userinfo = this.session('userinfo');
        console.log(userinfo.id)
        let db = this.model('basic_data');
        let data = this.post();
        data.created_by_id = 7;
        data.date_created = new Date().format("yyyy-MM-dd hh:mm:ss");
        data.last_updated = new Date().format("yyyy-MM-dd hh:mm:ss");
        let insertId = await db.add(data);
        this.ctx.body = {
            success: insertId > 0
        };
    }

    async findAction() {
        let result;
        let url = this.ctx.url;
        let db = this.model('basic_data');
        let resultObj = urlParse(url);
        for (let key in resultObj) {
            if (key == 'limit' || key == 'page')
                delete  resultObj[key];
        }
        let newObj = JSON.parse(JSON.stringify(resultObj));
        let json = {};
        for (let key in newObj) {
            json[key] = ['like', [`%${newObj[key]}%`]];
        }
        result = await db.where(json).page(this.get("page"), this.get("limit")).countSelect();
        result.code = 0;
        result.msg = "";

        return this.ctx.body = result;
    }

    async getBaseDataAction() {
        let db = this.model('basic_data');
        let result = await db.page(this.get("page")).countSelect();
        return this.jsonPage(result);
    }

    async deleteBaseDataAction() {
        let model = this.model('basic_data');
        if (this.isPost) {
            let data = this.post();
            let success = await model.where({id: data.id}).delete();
            return this.json(success);
        }
    }

    async storageRedisAction() {
        let data = this.post();
        let config = this.config('redis'); //获取 redis 配置
        data = JSON.parse(data.checkData);
        let client = await redis.createClient(config);
        client.on("error", function (err) {
            console.log("Error " + err);
            return;
        });

        client.on("connect", function () {
            console.log('连接成功！');
            let key_val = {};
            for (let i = 0; i < data.length; i++) {
                key_val.basic_key = data[i].basic_key;
                key_val.basic_value = data[i].basic_value;
                client.set('CACHE:basic', JSON.stringify(key_val));
                key_val = {};         //初始化
            }
            console.log(key_val)
            // client.set('CACHE:basic', 'Wilson', redis.print);
        });
        return;
    }
};
